<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务ID" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入任务ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="执行节点IP" prop="executeNodeIp">
        <el-input
          v-model="queryParams.executeNodeIp"
          placeholder="请输入执行节点IP"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.data_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建者" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:dataTaskLog:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:dataTaskLog:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:dataTaskLog:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['console:dataTaskLog:remove']"
          >清空</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:dataTaskLog:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataTaskLogList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"></span>
        </template>
      </el-table-column>
      <el-table-column label="编号" prop="id" align="center" />
      <el-table-column
        label="任务名称"
        width="180"
        align="center"
        prop="taskName"
      />
      <el-table-column label="任务类型" align="center" prop="taskType" />
      <el-table-column
        label="任务模式"
        align="center"
        width="160"
        prop="jobType"
      >
        <template slot-scope="scope">
          <div v-for="dict in dict.type.all_tasktype" :key="dict.value">
            <!-- {{ dict.value ==  ? dict.label : "" }} -->
            {{ dict.value == scope.row.jobType ? dict.label : "" }}
          </div>
        </template></el-table-column
      >
      <!-- <el-table-column label="任务ID" align="center" prop="taskId" /> -->
      <!-- <el-table-column label="任务报告" align="center" prop="taskReport" />
      <el-table-column label="任务日志" align="center" prop="taskLog" />
      <el-table-column label="程序日志" align="center" prop="programLog" /> -->
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <span v-for="dict in dict.type.taskstatus" :key="dict.value">
            <el-tag
              v-if="scope.row.taskStatus == dict.value"
              :type="dict.raw.listClass"
            >
              {{ dict.label }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="createTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />

      <!-- <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行节点IP" align="center" prop="executeNodeIp" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.data_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['console:dataTaskLog:edit']"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handelViewDetails(scope.row)"
            v-hasPermi="['console:dataTaskLog:remove']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:dataTaskLog:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <el-dialog
      title="同步结果"
      :visible.sync="asyncResult"
      width="75%"
      destroy-on-close
      v-if="asyncResultTable"
    >
      <div>
        <p>任务类型：{{ asyncResultTable.dataType }}</p>
        <p>任务信息：{{ asyncResultTable.message }}</p>
      </div>
      <el-table :data="asyncResultTable.items" height="300">
        <el-table-column label="对象名称" prop="objectName" />
        <el-table-column label="信息" prop="message" />
        <el-table-column label="堆栈错误信息" align="center" prop="errors">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleStack(scope.row)"
              v-hasPermi="['console:dataTaskconf:stack']"
              >查看堆栈</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="对象类型" align="center" prop="type">
          <template slot-scope="scope">
            <span
              v-for="dict in dict.type.appraise_taskmode"
              :key="dict.value"
              >{{ scope.row.type == dict.value ? dict.label : "" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="任务状态" align="center" prop="code">
          <template slot-scope="scope">
            <span v-for="dict in dict.type.taskstatus" :key="dict.value">
              <el-tag
                v-if="scope.row.code == dict.value"
                :type="dict.raw.listClass"
              >
                <!-- {{ scope.row.taskStatus }} -->
                {{ dict.label }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" />
        <el-table-column label="结束时间" align="center" prop="endTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRepair(scope.row)"
              :disabled="scope.row.code == 2"
              v-hasPermi="['console:dataTaskconf:Repair']"
              >修复</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleCheck(scope.row)"
              :disabled="scope.row.code == 2"
              v-hasPermi="['console:tasks:check']"
              >校验</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="asyncResult = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步结果"
      :visible.sync="codeEditorOpen"
      width="80%"
      destroy-on-close
    >
      <div class="codeBox">
        <div class="left">
          <el-divider content-position="left"><h2>源DDL</h2></el-divider>
          <CodeEditor
            :valueFontSize="12"
            :editorHight="300"
            :readOnly="true"
            :codeData="codeEditor.sourceCode"
          />
        </div>
        <div class="line">
          <svg
            t="1722844374330"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="7388"
            width="50"
            height="50"
          >
            <path
              d="M938.666667 512L640 761.6V262.4z"
              fill="#8a8a8a"
              p-id="7389"
            ></path>
            <path
              d="M128 426.666667h576v170.666666H128z"
              fill="#8a8a8a"
              p-id="7390"
            ></path>
          </svg>
        </div>
        <div class="right">
          <el-divider content-position="left"><h2>目标DDL</h2></el-divider>
          <CodeEditor
            ref="codeEditor"
            :valueFontSize="12"
            :editorHight="300"
            :codeData="codeEditor.sinkCode"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-loading="repairLoading"
          @click="handleRunDll"
          >修 复</el-button
        >
        <el-button type="primary" @click="codeEditorOpen = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="堆栈错误信息"
      :visible.sync="dialogStackVisible"
      width="75%"
    >
      <pre><code>{{ stackErrorsMsg }}</code></pre>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStackVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDataTaskLog,
  getDataTaskLog,
  delDataTaskLog,
  addDataTaskLog,
  updateDataTaskLog,
} from "@/api/console/dataTaskLog";

import { delDataTaskconfVerify } from "@/api/console/dataTaskconf";

import CodeEditor from "@/components/CodeEditor/index.vue";


import { sqlTaskExecuteSql } from "@/api/console/executeSql";

export default {
  name: "DataTaskLog",
  components: { CodeEditor },
  dicts: [
    "all_tasktype",
    "appraise_taskmode",
    "data_status",
    "taskstatus",
    "synchronous_tasktype",
    "appraise_tasktype",
    "check_tasktype",
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务日志表格数据
      dataTaskLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        taskType: null,
        jobType: null,
        taskId: null,
        taskName: null,
        taskReport: null,
        taskLog: null,
        programLog: null,
        taskStatus: null,
        startTime: null,
        endTime: null,
        executeNodeIp: null,
        status: null,
        createBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      asyncResult: false,
      asyncResultTable: [],
      verifyData: null,
      codeEditorOpen: false,
      codeEditor: {
        sourceCode: "",
        sinkCode: "",
      },
      dialogStackVisible: null,
      stackErrorsMsg: "",
      repairLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleCheck(row) {
      let that = this;
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认校验配置编号为"' + that.verifyData.id + '"的数据项？')
        .then(function () {
          return delDataTaskconfVerify({
            id: that.verifyData.id,
            taskTypeScope: row.type,
            name: row.objectName,
          });
        })
        .then(() => {
          // this.getList();
          this.$modal.msgSuccess("校验成功");
        })
        .catch(() => {});
    },
    handleStack(row) {
      if (!row.errors) {
        return this.$message.warning("暂无错误信息");
      }
      this.dialogStackVisible = true;
      this.stackErrorsMsg = row.errors;
    },
    async handleRepair(row) {
      this.codeEditorOpen = true;
      this.codeEditor.sourceCode = row.sourceDdl;
      this.codeEditor.sinkCode = row.sinkDdl || "";
    },
    handelViewDetails(row) {
      if (row.taskStatus != 2) {
        return this.$message.warning("任务未成功");
      }
      Promise.all([
        this.getDicts("synchronous_tasktype"),
        this.getDicts("appraise_tasktype"),
        this.getDicts("check_tasktype"),
      ]).then((res) => {
        let path;
        if (res[0].data.some((f) => f.dictValue == row.jobType)) {
          this.asyncResult = true;
          this.handleTaskResult(row);
          return;
        }
        if (res[1].data.some((f) => f.dictValue == row.jobType)) {
          path = `/report/assessmentReport?id=${row.id}`;
        }
        if (res[2].data.some((f) => f.dictValue == row.jobType)) {
          path = `/report/verificationReport?id=${row.id}`;
        }
        window.open(path);
      });
      // let type = this.$route.query.type;
      // let path;
    },
    async handleRunDll() {
      this.repairLoading = true;
      try {
        await sqlTaskExecuteSql({
          datasourceId: this.verifyData.id,
          sqlContext: this.$refs.codeEditor._data.content,
        });
        this.$message.error("修复成功");
        this.repairLoading = false;
        this.codeEditorOpen = false;
      } catch (error) {
        this.$message.error(error);
        this.repairLoading = false;
      }
    },
    async handleTaskResult(row) {
      this.verifyData = row;
      this.asyncResult = true;
      const tableData = JSON.parse(row.taskResult);
      this.asyncResultTable = tableData;
      if (tableData.items.length > 0) {
        return;
      }
      let newTableData = [];
      Object.keys(tableData.data).forEach((f) => {
        tableData.data[f].items.forEach((j) => {
          newTableData.push({
            ...j,
            taskType: f,
          });
        });
      });
      this.asyncResultTable.items = newTableData;
    },
    getIndex($index) {
      return (
        (this.queryParams.pgNum - 1) * this.queryParams.pgSize + $index + 1
      );
    },
    /** 查询任务日志列表 */
    getList() {
      this.loading = true;
      listDataTaskLog(this.queryParams).then((response) => {
        this.dataTaskLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskType: null,
        jobType: null,
        taskId: null,
        taskName: null,
        taskReport: null,
        taskLog: null,
        programLog: null,
        taskStatus: null,
        startTime: null,
        endTime: null,
        executeNodeIp: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务日志";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDataTaskLog(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务日志";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // if (this.form.id != null) {
          //   updateDataTaskLog(this.form).then((response) => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addDataTaskLog(this.form).then((response) => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
          addDataTaskLog(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除任务日志编号为"' + ids + '"的数据项？')
        .then(function () {
          return delDataTaskLog({ idArray: Array.isArray(ids) ? ids : [ids] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "console/dataTaskLog/export",
        {
          ...this.queryParams,
        },
        `dataTaskLog_${new Date().getTime()}.xlsx`
      );
    },
    /** 清空按钮操作 */
    handleClean() {
      this.$modal
        .confirm("是否确认清空所有任务日志数据项？")
        .then(function () {
          return delDataTaskLog({ ids: [] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("清空成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
h2 {
  margin: 0;
}

pre {
  height: 400px;
  padding: 15px 0;
  overflow: auto;
}

.codeBox {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .left,
  .right {
    width: 45%;
  }

  .line {
    width: 5%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.textBox {
  height: 300px;
  overflow-y: auto;
}
</style>
